package com.example.personalaccount.service.impl;
import com.example.personalaccount.entity.Clause;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service("excelExportService")
public class ExcelExportService {

    public byte[] generateExcel (List<Clause> clauses) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(""+ LocalDate.now() + "导出");

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        String[] headers = {"ID", "OriginAccount", "DestinationAccount", "Amount", "Flag", "Function" , "Remark","Time"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        int rowNum = 1;
        for (Clause clause : clauses) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(clause.getId());
            row.createCell(1).setCellValue(clause.getOriginAccount());
            row.createCell(2).setCellValue(clause.getDestinationAccount());
            row.createCell(3).setCellValue(clause.getAmount());
            row.createCell(4).setCellValue(clause.isFlag() ? "支出" : "收入");
            row.createCell(5).setCellValue(clause.getFunc());
            row.createCell(6).setCellValue(clause.getRemark());
            row.createCell(7).setCellValue(clause.getTimeStamp().format(formatter));
        }

        // 将工作簿写入字节数组输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();

        return outputStream.toByteArray();
    }
}